#-*- encoding:UTF-8 -*-
import wx
import wx.grid
import xlrd
import socket
import os
import struct
import string
import seq_socket

#dwType=530
#dwNetId=0
#dwEdId=1
#acData="1234\0"
#s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
#data=struct.pack('II',dwType, dwNetId, dwEdId, acData)

class TestTable(wx.grid.PyGridTableBase):#定义网格表

    def __init__(self):
        wx.grid.PyGridTableBase.__init__(self)
        

            
        self.data = { (1,1) : "Here",
                      (2,2) : "is",
                      (3,3) : "some",
                      (4,4) : "data",
                      }
        
        self.odd=wx.grid.GridCellAttr()
        self.odd.SetBackgroundColour("sky blue")
        self.odd.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))
        self.even=wx.grid.GridCellAttr()
        self.even.SetBackgroundColour("sea green")
        self.even.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))
    # these ﬁve are the required methods
    def GetNumberRows(self):
        return 20
    def GetNumberCols(self):
        return len(self.colLabels)
    def IsEmptyCell(self, row, col):
        return self.data.get((row, col)) is not None
    def GetValue(self, row, col):#为网格提供数据
        value = self.data.get((row, col))
        if value is not None:
            return value
        else:
            return ''
    def SetValue(self, row, col, value):#给表赋值
        self.data[(row,col)] = value
    # the table can also provide the attribute for each cell
    def GetAttr(self, row, col, kind):
        attr = [self.even, self.odd][row % 2]
        attr.IncRef()
        return attr

class GridFrame(wx.Frame):
    rowLabels = ["雷管地址"]
    colLabels = ["雷管序号", "网络编号", "雷管ID号码", "地址编号", "地址设定", "延时时间（ms）", "延时设定", "储能电压", "密码", "校时", "雷管信息"]
    def __init__(self):
        wx.Frame.__init__(self, None, title="Grid Table",
                          size=(990,450))
        self.grid = wx.grid.Grid(self)
        #table = TestTable()
        #grid.SetTable(table, True)
        self.grid.CreateGrid(20, len(self.colLabels))
        
        #重定向grid的close
        self.Bind(wx.EVT_CLOSE, self.OnHideGrid)
        
        for col in range(len(self.colLabels)):
            self.grid.SetColLabelValue(col, self.colLabels[col])
    
    def OnHideGrid(self, event):
        self.Hide()
        
    def ReadData(self):
        print 'open rdata.xls'
        data = xlrd.open_workbook('RData.xls')
        table = data.sheets()[0] 
        nrows = table.nrows
        ncols = table.ncols
        for row in range(nrows ):
            for col in range(ncols ):
                cont = table.row_values(row)[col]
                self.grid.SetCellValue(row, col, "(%s)" % (cont))

class PageInfo(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        t = wx.StaticText(self, -1, "PageInfo", (20,20))

                
class ButtonFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, 'EDMS', 
                size=(1200, 700))
        panel = wx.Panel(self, -1)

        # buttons on the left
        size_btn = (110, -1)
        
        #起爆密码
        wx.StaticText(panel, -1, "起爆密码:", pos=(20, 5))
        self.pwdText = wx.TextCtrl(panel, -1, "111111", size=size_btn, pos=(20, 25), style=wx.TE_PASSWORD)
        
        #初始ID
        wx.StaticText(panel, -1, "初始ID:", pos=(20, 45))
        self.idStartInput = wx.TextCtrl(panel, -1, "E0 38 45 34 70", size=size_btn, pos=(20, 65))       
 
        #结束ID
        wx.StaticText(panel, -1, "结束ID:", pos=(20, 85))
        self.idEndInput = wx.TextCtrl(panel, -1, "E0 38 45 E0 80", size=size_btn, pos=(20, 105)) 
               
        #搜索全部网络
        self.BtnSrhAllNet = wx.Button(panel, -1, "搜索全部网络", size=size_btn, pos=(20, 135))
        self.Bind(wx.EVT_BUTTON, self.SrchAllNet, self.BtnSrhAllNet)
        self.BtnSrhAllNet.SetDefault()
        
        #设定通讯地址
        self.BtnSetCommAddr = wx.Button(panel, -1, "设定通讯地址", size=size_btn, pos=(20, 165))
        self.Bind(wx.EVT_BUTTON, self.SetCommAddr, self.BtnSetCommAddr)
        self.BtnSetCommAddr.SetDefault()
        
        #校验通讯地址
        self.BtnChkCommAddr = wx.Button(panel, -1, "校验通讯地址", size=size_btn, pos=(20, 195))
        self.Bind(wx.EVT_BUTTON, self.ChkCommAddr, self.BtnChkCommAddr)
        self.BtnChkCommAddr.SetDefault()    
        
        #设定延时时间
        self.BtnSetDlyTime = wx.Button(panel, -1, "设定延时时间", size=size_btn, pos=(20, 225))
        self.Bind(wx.EVT_BUTTON, self.SetDlyTime, self.BtnSetDlyTime)
        self.BtnSetDlyTime.SetDefault()       
        
        #校验延时时间
        self.BtnChkDlyTime = wx.Button(panel, -1, "校验延时时间", size=size_btn, pos=(20, 255))
        self.Bind(wx.EVT_BUTTON, self.ChkDlyTime, self.BtnChkDlyTime)
        self.BtnChkDlyTime.SetDefault()   
        
        #密码校验
        self.BtnBusPowerOn = wx.Button(panel, -1, "总线供电", size=size_btn, pos=(20, 285))
        self.Bind(wx.EVT_BUTTON, self.BusPowerOn, self.BtnBusPowerOn)
        self.BtnBusPowerOn.SetDefault()        

        #读取储能电压e
        self.BtnReadSavePow = wx.Button(panel, -1, "读取储能电压", size=size_btn, pos=(20, 315))
        self.Bind(wx.EVT_BUTTON, self.ReadSavePow, self.BtnReadSavePow)
        self.BtnReadSavePow.SetDefault() 
        
        #校对晶振
        self.BtnSetNetTime = wx.Button(panel, -1, "校对晶振", size=size_btn, pos=(20, 345))
        self.Bind(wx.EVT_BUTTON, self.SetNetTime, self.BtnSetNetTime)
        self.BtnSetNetTime.SetDefault() 
        
        #ShowTable
        self.BtnDisplay = wx.Button(panel, -1, "显示雷管信息", size=size_btn, pos=(20, 375))
        self.Bind(wx.EVT_BUTTON, self.Fire, self.BtnDisplay)
        self.BtnDisplay.SetDefault() 

        #充电 
        self.BtnCharge = wx.Button(panel, -1, "充电", size=size_btn, pos=(150, 415))
        self.Bind(wx.EVT_BUTTON, self.Charge, self.BtnCharge)
        self.BtnCharge.SetDefault() 

        #起爆 
        self.BtnFire = wx.Button(panel, -1, "起爆", size=size_btn, pos=(270, 415))
        self.Bind(wx.EVT_BUTTON, self.Fire, self.BtnFire)
        self.BtnFire.SetDefault() 
        
        #一键 
        self.BtnOneKey = wx.Button(panel, -1, "OneKey", size=size_btn, pos=(390, 415))
        self.Bind(wx.EVT_BUTTON, self.OneKey, self.BtnOneKey)
        self.BtnOneKey.SetDefault() 

        #雷管ID
        wx.StaticText(panel, -1, "雷管ID:", pos=(20, 405))
        self.EDId = wx.TextCtrl(panel, -1, "0", size=size_btn, pos=(20, 425)) 
        #雷管MAC
        wx.StaticText(panel, -1, "雷管MAC:", pos=(20, 455))
        
        self.EDMac = wx.TextCtrl(panel, -1, "12 34 56 78 9B", size=size_btn, pos=(20, 475)) 
        #网络ID
        wx.StaticText(panel, -1, "网络ID:", pos=(20, 505))
        self.EDNetId = wx.TextCtrl(panel, -1, "1", size=size_btn, pos=(20, 525)) 
        
        #网络ID
        wx.StaticText(panel, -1, "延时时间:", pos=(20, 555))
        self.DlyTime = wx.TextCtrl(panel, -1, "1", size=size_btn, pos=(20, 575))   
        wx.StaticText(panel, -1, "ms", pos=(120, 580))

        #Grid
        rowLabels = ["雷管地址"]
        colLabels = ["雷管序号", "网络编号", "雷管ID号码", "地址编号", "地址设定", "延时时间（ms）", "延时设定", "储能电压", "密码", "校时", "雷管信息"]
        self.gridTable = wx.grid.Grid(parent=panel, size=(1000,400), pos=(150, 5))       
        self.gridTable.CreateGrid(20, len(colLabels))
        for col in range(len(colLabels)):
            self.gridTable.SetColLabelValue(col, colLabels[col])
        self.ReadData()

        #logInfo
        #NtBook = wx.Notebook(panel)
        #PageInf = PageInfo(NtBook)
        #NtBook.AddPage(PageInf, "Info")
        wx.StaticText(panel, -1, "操作记录", pos=(150, 440))
        self.LogInfo = wx.TextCtrl(panel, -1, size=(1000, 200), pos=(150, 460), style=wx.TE_MULTILINE)
        
        #self.gridTable = GridFrame()
        
        self.GridEdNum = 0
        
        self.GridLableEdNum = 0
        self.GridLableNetId = 1
        self.GridLableEdId = 2
        self.GridLableEdMac = 3
        self.GridLableAddrSetTag = 4
        self.GridLableDlyTime = 5
        self.GridLableDlyTimeSetTag = 6
        self.GridLableSavePower = 7
        self.GridLablePassWord = 8
        self.GridLableChkTime = 9
        self.GridLableEdInfo = 10
        
        self.SerialHostIp = '192.168.1.10'
        self.SerialHostPort = 5555
    
    def ReadData(self):
        data = xlrd.open_workbook('RData.xls')
        table = data.sheets()[0] 
        nrows = table.nrows
        ncols = table.ncols
        for row in range(nrows ):
            for col in range(ncols ):
                cont = table.row_values(row)[col]
                self.gridTable.SetCellValue(row, col, "(%s)" % (cont))

    def SrchAllNet(self, event):
        self.idStart = self.idStartInput.GetValue()
        self.LogInfo.AppendText(self.idStart + '\r\n')
        self.BtnSrhAllNet.SetLabel("搜索全部网络")
        
    def SetCommAddr(self, event):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)        
        EDIdInput = self.EDId.GetValue()
        EDMacInput = self.EDMac.GetValue()
        EDNetIdInput = self.EDNetId.GetValue()
        
        EDMacInputList = EDMacInput.split(' ')
        #Mac1 = hex(int(EDMacInputList[0], 16))
        #Mac2 = hex(int(EDMacInputList[1], 16))
        #Mac3 = hex(int(EDMacInputList[2], 16))
        #Mac4 = hex(int(EDMacInputList[3], 16))
        #Mac5 = hex(int(EDMacInputList[4], 16))
        #print Mac1,Mac2,Mac3,Mac4,Mac5

        self.LogInfo.AppendText('设定通讯地址' + "\r\n")
        self.LogInfo.AppendText('EDMacInput ' + EDMacInput + "\r\n")
        self.LogInfo.AppendText('EDIdInput ' + EDIdInput + "\r\n")
        self.LogInfo.AppendText('EDNetIdInput ' + EDNetIdInput + "\r\n")
        
        for row in range(self.gridTable.GetNumberRows()):                
            if (self.gridTable.GetCellValue(row, self.GridLableEdMac) == EDMacInput):                        
                self.gridTable.SetCellValue(row, self.GridLableEdNum, "%s" % (1))
                self.gridTable.SetCellValue(row, self.GridLableNetId, "%s" % (EDNetIdInput))
                self.gridTable.SetCellValue(row, self.GridLableEdId, "%s" % (EDIdInput))
                self.gridTable.SetCellValue(row, self.GridLableEdMac, "%s" % (EDMacInput))
                self.gridTable.SetCellValue(row, self.GridLableAddrSetTag, "%s" % ('N'))
                self.gridTable.SetCellValue(row, self.GridLableDlyTime, "%s" % ('0'))
                self.gridTable.SetCellValue(row, self.GridLableDlyTimeSetTag, "%s" % ('N'))
                self.gridTable.SetCellValue(row, self.GridLableSavePower, "%s" % ('0'))        
                self.gridTable.SetCellValue(row, self.GridLablePassWord, "%s" % ('Y'))      
                self.gridTable.SetCellValue(row, self.GridLableChkTime, "%s" % ('12'))  
                self.gridTable.SetCellValue(row, self.GridLableEdInfo, "%s" % ('12')) 
                break
            else:            
                self.gridTable.SetCellValue(self.GridEdNum, self.GridLableEdNum, "%s" % (1))
                self.gridTable.SetCellValue(self.GridEdNum, self.GridLableNetId, "%s" % (EDNetIdInput))
                self.gridTable.SetCellValue(self.GridEdNum, self.GridLableEdId, "%s" % (EDIdInput))
                self.gridTable.SetCellValue(self.GridEdNum, self.GridLableEdMac, "%s" % (EDMacInput))
                self.gridTable.SetCellValue(self.GridEdNum, self.GridLableAddrSetTag, "%s" % ('N'))
                self.gridTable.SetCellValue(self.GridEdNum, self.GridLableDlyTime, "%s" % ('0'))
                self.gridTable.SetCellValue(self.GridEdNum, self.GridLableDlyTimeSetTag, "%s" % ('N'))
                self.gridTable.SetCellValue(self.GridEdNum, self.GridLableSavePower, "%s" % ('0'))        
                self.gridTable.SetCellValue(self.GridEdNum, self.GridLablePassWord, "%s" % ('Y'))      
                self.gridTable.SetCellValue(self.GridEdNum, self.GridLableChkTime, "%s" % ('12'))  
                self.gridTable.SetCellValue(self.GridEdNum, self.GridLableEdInfo, "%s" % ('12'))  
                self.GridEdNum = self.GridEdNum + 1    
                        
        SetAddrMsg = struct.pack('!3l5B', 1154, string.atoi(EDNetIdInput), string.atoi(EDIdInput), int(EDMacInputList[0], 16), int(EDMacInputList[1], 16), int(EDMacInputList[2], 16), int(EDMacInputList[3], 16), int(EDMacInputList[4], 16))
        #self.LogInfo.AppendText(SetAddrMsg)
        self.LogInfo.AppendText(repr(SetAddrMsg) + "\r\n")
        self.LogInfo.AppendText("\r\n")


        #self.LogInfo.AppendText('unpack EDIdInput ' + str(a2) + " ")
        #self.LogInfo.AppendText('unpack EDNetIdInput ' + str(a3) + "\r\n")
        #print a1, a2, a3, hex(a4)

        #sock.sendto(SetAddrMsg, ('192.168.1.10', 5555))
        sock.sendto(SetAddrMsg, (self.SerialHostIp, self.SerialHostPort))
        #RcvBuf, RcvAddr = sock.recvfrom(1024)
        #print RcvBuf
        self.LogInfo.AppendText(repr(RcvBuf) + "\r\n") 
        EDMacRcvList = [0, 0, 0, 0, 0]
        EDMacRcv = ''
        MsgIdRcv, EDNetIdRcv, EDIdRcv, EDMacRcvList[0], EDMacRcvList[1] ,EDMacRcvList[2], EDMacRcvList[3] , EDMacRcvList[4]= struct.unpack('!3l5B', RcvBuf)
        
        print len(EDMacRcvList)
        
        for idx in range(len(EDMacRcvList)):
            EDMacRcv += str(hex(EDMacRcvList[idx]).upper()[2:])
            if (idx < (len(EDMacRcvList) - 1)):
                EDMacRcv += " "
        print EDMacRcv
        #1281 OK
        #print int(MsgIdRcv)
        if int(MsgIdRcv) == 1281:
            self.LogInfo.AppendText("Set Addr Success! \r\n\r\n")
            for row in range(self.gridTable.grid.GetNumberRows()):                
                if (self.gridTable.grid.GetCellValue(row, self.GridLableEdMac) == EDMacRcv):                        
                    self.gridTable.grid.SetCellValue(row, self.GridLableAddrSetTag, "%s" % ('Y'))
        else:
            if int(MsgIdRcv) == 1282:
                self.LogInfo.AppendText("Set Addr Fail! \r\n\r\n")
            else:
                self.LogInfo.AppendText("Get Err Msgid \r\n\r\n")
            

        sock.close();
        #self.LogInfo.AppendText("end of connect" + "\r\n")

        self.BtnSetCommAddr.SetLabel("设定通讯地址")
        
    def ChkCommAddr(self, event):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)        
        EDIdInput = self.EDId.GetValue()
        #EDMacInput = self.EDMac.GetValue()
        EDNetIdInput = self.EDNetId.GetValue()
        
        #EDMacInputList = EDMacInput.split(' ')
        #Mac1 = hex(int(EDMacInputList[0], 16))
        #Mac2 = hex(int(EDMacInputList[1], 16))
        #Mac3 = hex(int(EDMacInputList[2], 16))
        #Mac4 = hex(int(EDMacInputList[3], 16))
        #Mac5 = hex(int(EDMacInputList[4], 16))
        #print Mac1,Mac2,Mac3,Mac4,Mac5

        self.LogInfo.AppendText('校验通讯地址' + "\r\n")
        #self.LogInfo.AppendText('EDMacInput ' + EDMacInput + "\r\n")
        self.LogInfo.AppendText('EDIdInput ' + EDIdInput + "\r\n")
        self.LogInfo.AppendText('EDNetIdInput ' + EDNetIdInput + "\r\n")
        
        ChkAddrMsg = struct.pack('!3l', 1155, string.atoi(EDNetIdInput), string.atoi(EDIdInput))
        #self.LogInfo.AppendText(ChkAddrMsg)
        self.LogInfo.AppendText(repr(ChkAddrMsg) + "\r\n")
        self.LogInfo.AppendText("\r\n")

        #sock.sendto(ChkAddrMsg, ('10.30.141.220', 5555))
        sock.sendto(ChkAddrMsg, (self.SerialHostIp, self.SerialHostPort))
        #RcvBuf = sock.recvfrom(1024)
        #self.LogInfo.AppendText("recv " + szBuf + "\r\n")
        sock.close();
        #self.LogInfo.AppendText("end of connect" + "\r\n")

        self.BtnChkCommAddr.SetLabel("校验通讯地址")
        
    def SetDlyTime(self, event):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  
        EDNetIdInput = self.EDNetId.GetValue()      
        EDIdInput = self.EDId.GetValue()
        DlyTimeInput = self.DlyTime.GetValue()
        
        self.LogInfo.AppendText('设定延时时间' + "\r\n")
        self.LogInfo.AppendText('EDNetIdInput ' + EDNetIdInput + "\r\n")
        self.LogInfo.AppendText('EDIdInput ' + EDIdInput + "\r\n")
        self.LogInfo.AppendText('DlyTimeInput ' + DlyTimeInput + "\r\n")
        
        for row in range(self.gridTable.grid.GetNumberRows()):               
            if (self.gridTable.grid.GetCellValue(row, self.GridLableEdId) == EDIdInput):
                self.gridTable.grid.SetCellValue(row, self.GridLableDlyTime, "%s" % (DlyTimeInput))
                self.gridTable.grid.SetCellValue(row, self.GridLableDlyTimeSetTag, "%s" % ('N'))
                break
        else:
            self.LogInfo.AppendText('EDIdInput ' + EDIdInput + "isn't exit!\r\n")
            return
        
        SetDlyTimeMsg = struct.pack('!4l', 1156, string.atoi(EDNetIdInput), string.atoi(EDIdInput), string.atoi(DlyTimeInput))
        #self.LogInfo.AppendText(SetDlyTimeMsg)
        self.LogInfo.AppendText(repr(SetDlyTimeMsg) + "\r\n")
        self.LogInfo.AppendText("\r\n")

        #sock.sendto(SetDlyTimeMsg, ('10.30.141.220', 5555))
        sock.sendto(SetDlyTimeMsg, (self.SerialHostIp, self.SerialHostPort))
        #RcvBuf = sock.recvfrom(1024)
        #self.LogInfo.AppendText("RcvBuf " + RcvBuf + "\r\n")
        sock.close();
        #self.LogInfo.AppendText("end of connect" + "\r\n")
        
        self.BtnSetDlyTime.SetLabel("设定延时时间")  
           
    def ChkDlyTime(self, event):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)   
        EDNetIdInput = self.EDNetId.GetValue()     
        EDIdInput = self.EDId.GetValue()
        
        self.LogInfo.AppendText('校验延时时间' + "\r\n")
        self.LogInfo.AppendText('EDIdInput ' + EDIdInput + "\r\n")
        
        ChkDlyTimeMsg = struct.pack('!3l', 1157, string.atoi(EDNetIdInput), string.atoi(EDIdInput))
        #sock.sendto(ChkDlyTimeMsg, (self.SerialHostIp, self.SerialHostPort))
        #RcvBuf = sock.recvfrom(1024)
        
        #sock.close();       
        self.BtnChkDlyTime.SetLabel("校验延时时间")     
        
    def BusPowerOn(self, event):
        self.LogInfo.AppendText('总线供电' + "\r\n")
        self.LogInfo.AppendText("\r\n")
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
        
        BusPowerOnMsg = struct.pack('!1l', 1161)
        sock.sendto(BusPowerOnMsg, (self.SerialHostIp, self.SerialHostPort))
        #RcvBuf = sock.recvfrom(1024)
        
        sock.close();               
        
        self.BtnBusPowerOn.SetLabel("总线供电")    

    def ReadSavePow(self, event):
        self.BtnReadSavePow.SetLabel("读取储能电压")   
        
    def SetNetTime(self, event):
        self.LogInfo.AppendText('校对晶振' + "\r\n")
        self.LogInfo.AppendText("\r\n")
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
        
        SetNetTimeMsg = struct.pack('!1l', 1163)
        sock.sendto(SetNetTimeMsg, (self.SerialHostIp, self.SerialHostPort))
        #RcvBuf = sock.recvfrom(1024)
        
        sock.close();               
        
        self.BtnSetNetTime.SetLabel("校对晶振")   

    def DisPlayInfo(self, event):
        self.BtnDisplay.SetLabel("显示雷管信息")  
        #self.gridTable.Show()
        #self.gridTable.ReadData()
        
    def Charge(self, event):
        self.LogInfo.AppendText('充电' + "\r\n")
        self.LogInfo.AppendText("\r\n")
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
        
        ChargeMsg = struct.pack('!1l', 1164)
        sock.sendto(ChargeMsg, (self.SerialHostIp, self.SerialHostPort))
        #RcvBuf = sock.recvfrom(1024)
        
        sock.close();    
        self.BtnCharge.SetLabel("充电")  
    
    '''
    def callback(self, rcv):
        print rcv    
    '''

    def Fire(self, event):
        self.LogInfo.AppendText('起爆' + "\r\n")
        self.LogInfo.AppendText("\r\n")
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
        
        FireMsg = struct.pack('!1l', 1166)

        '''
        a = seq_socket.seq_socket()
        a.set_config('localhost', 17800)
        a.send('test fire!', self.callback)
        '''

        sock.sendto(FireMsg, (self.SerialHostIp, self.SerialHostPort))
        #RcvBuf = sock.recvfrom(1024)

        
        sock.close();    
        self.BtnFire.SetLabel("起爆")  
        
    def OneKey(self, event):
        self.BusPowerOn(event)
        self.SetNetTime(event)
        self.SetCommAddr(event)
        self.SetDlyTime(event)
        self.Charge(event)
        self.Fire(event)
        
        
if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = ButtonFrame()
    frame.Show()
    app.MainLoop()
